#include "BufferIPC.hpp"
#include "BufferImage.hpp"
#include "Client_types.h"
#include "DeviceObj.hpp"
#include <iostream>
#include <string>
#define STB_IMAGE_WRITE_IMPLEMENTATION
#include <stb/stb_image_write.h>

BufferIPC buffer;

int main() {
  std::string Addr;
  long ClientPort;
  long BroadcastPort;
  std::cout << "Please Input Address: ";
  std::cin >> Addr;
  std::cout << "Please Input Client Port: ";
  std::cin >> ClientPort;
  std::cout << "Please Input Broadcast Port: ";
  std::cin >> BroadcastPort;
  buffer.Boot(Addr, ClientPort, BroadcastPort);
  auto list = buffer.GetDeviceList();
  if (list.empty()) {
    std::cout << "Current List is empty" << std::endl;
    return 0;
  } else {
    std::cout << "Scan Camera List: " << std::endl;
    int index = 0;
    for (const auto &i : list) {
      std::cout << index << ": " << i << std::endl;
      index++;
    }
  }
  std::cout << "Please Input select Camera Index: ";
  long index;
  std::cin >> index;
  auto device = buffer.GetDevice(list[index]);
  device->UpdateFormat();
  if (device != nullptr) {
    BufferImage img = device->Get();
    long channel;
    switch (img.type) {
    case Thrift::ImageFormat::type::GERY:
      channel = 1;
      break;
    case Thrift::ImageFormat::type::RGB8:
      channel = 3;
      break;
    default:
      std::cout << "Unknow Image Type, Please Update Program" << std::endl;
      return 0;
    }
    stbi_write_bmp("Buffer.bmp", img.width, img.height, channel, img.data);
    delete img.data;
  }
  return 0;
}
